﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="BlockedReports.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using GenericTools;
using System.Drawing;
using DataModels.Enumerations;
using DataModels.Common;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        private bool tabPageBlockedReportsLoaded = false;
        DataTable blockedReports = null;
        private int blockedReportCount = 0;

        private void tabPageBlockedReports_Enter(object sender, EventArgs e)
        {
            if (!tabPageBlockedReportsLoaded)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.DISTRICT:
                            int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            blockedReports = Utilities.GetBlockedReportsByDistrict(districtID);
                            break;

                        case AccessLevel.REGION:
                            int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            blockedReports = Utilities.GetBlockedReportsByRegion(regionID, this.authenticatedUser.SupportingPartnerId);
                            break;

                        case AccessLevel.NATION:
                            blockedReports = Utilities.GetBlockedReports(this.authenticatedUser.SupportingPartnerId);
                            break;

                        case AccessLevel.ADMINISTRATOR:
                            blockedReports = Utilities.GetBlockedReports();
                            break;
                    }                    
                    Cursor.Current = Cursors.Default;

                    PopulateBlockedReports();
                    tabPageBlockedReportsLoaded = true;

                    if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                        (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                    {
                        btnRefreshBlockedList.Enabled = false;
                        btnViewReportingHistory.Enabled = false;
                        cmdUnblock.Enabled = false;
                    }
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }

            //cmdUnblock.Enabled = (blockedReportCount > 0);
        }

        private void dgvBlockedReports_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                lblBDateReceived.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["DateReceived"].Value.ToString();
            } catch { }
            try
            {
                lblBReportName.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["ReportName"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRErrMsg.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["ErrMsg"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRFacCode.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["FacCode"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRFacName.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["FacName"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRPeriod.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["Period"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRRegion.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["RegionName"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRDistrict.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["DistrictName"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRRepDetails.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["TxtDetails"].Value.ToString();
            }
            catch { }
            try
            {
                lblBRYear.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["Year"].Value.ToString();
            }
            catch { }
            try
            {
                lblBSenderName.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["Name"].Value.ToString();
            }
            catch { }
            try
            {
                lblBSenderNum.Text = dgvBlockedReports.Rows[e.RowIndex].Cells["SenderNum"].Value.ToString();
            }
            catch { }
        }

        private void btnViewReportingHistory_Click(object sender, EventArgs e)
        {
            try
            {
                btnViewReportingHistory.Enabled = false;
                Application.DoEvents();
                if (dgvBlockedReports.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = dgvBlockedReports.SelectedRows[0];
                    string phoneNumber = row.Cells["SenderNum"].Value.ToString();
                    MessageHistory messageHistory = new MessageHistory(phoneNumber);
                    messageHistory.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
            finally
            {
                btnViewReportingHistory.Enabled = true;
            }
        }

        private void cmdUnblock_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            DialogResult response = MessageBox.Show(this, 
                String.Format("Do you want to unblock this report?"), 
                String.Format("{0} - Unblock Report", AppConfiguration.ApplicationName), 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (response == System.Windows.Forms.DialogResult.Yes)
            {
                DataGridViewRow dgvDetails = dgvBlockedReports.CurrentRow;
                string senderNumber = dgvDetails.Cells["SenderNum"].Value.ToString();
                //int report = Int32.Parse(dgvDetails.Cells["RepID"].Value.ToString());
                //string facilityCode = dgvDetails.Cells["FacCode"].Value.ToString();
                //int year = Int32.Parse(dgvDetails.Cells["Year"].Value.ToString());
                //int period = Int32.Parse(dgvDetails.Cells["Period"].Value.ToString());

                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    cmdUnblock.Enabled = false;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    //Utilities.DeleteBlockedReport(report, facilityCode, period, year);
                    Utilities.DeleteBlockedUserReport(senderNumber); 
                    
                    //string filterExpression = String.Format("SenderNum = {0}", senderNumber);
                    //DataRow[] rows = blockedReports.Select(filterExpression);
                    //for (int i = 0; i < rows.Length; i++) blockedReports.Rows.Remove(rows[i]);

                    //List<DataRow> rowsToDelete = new List<DataRow>();
                    //for (int i = 0; i < blockedReports.Rows.Count; i++)
                    //{
                    //    DataRow row = blockedReports.Rows[i];
                    //    string number = row["SenderNum"].ToString();
                    //    if (number == senderNumber) rowsToDelete.Add(row);
                    //}
                    //for (int i = 0; i < rowsToDelete.Count; i++) blockedReports.Rows.Remove(rowsToDelete[i]);

                    //PopulateBlockedReports();
                    //cmdUnblock.Enabled = true;

                    foreach (DataGridViewRow r in dgvBlockedReports.Rows)
                    {
                        DataRowView rowView = r.DataBoundItem as DataRowView;
                        if (rowView != null)
                        {
                            string number = rowView["SenderNum"].ToString();
                            if (number == senderNumber) rowView.Delete();
                        }
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    cmdUnblock.Enabled = (dgvBlockedReports.Rows.Count > 0);
                    if (string.IsNullOrEmpty(txtSearchBlockedReports.Text))
                    {
                        lblBlockedCount.Text = String.Format("There are {0} blocked reporting", 
                            dgvBlockedReports.Rows.Count);
                        lblBlockedCount.ForeColor = Color.Black;
                    }
                    else
                    {
                        lblBlockedCount.Text = string.Format("Search Results: {0} blocked reporting", dgvBlockedReports.Rows.Count);
                        lblBlockedCount.ForeColor = Color.BlueViolet;
                    }
                    

                    //Cursor.Current = Cursors.WaitCursor;
                    //toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();                    

                    //if (AppConfiguration.DataCached) dgvBlockedReports.Rows.Remove(dgvDetails);
                    //else
                    //{
                    //    Cursor.Current = Cursors.WaitCursor;
                    //    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    //    dtErrReps = Utilities.GetBlockedReports();
                    //    PopulateBlockedReports(dtErrReps);
                    //    Cursor.Current = Cursors.Default;
                    //    toolStripStatusLabel.Text = "Ready";
                    //}
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void  PopulateBlockedReports()
        {
            if (blockedReports.Rows.Count > 0)
            {
                this.dgvBlockedReports.DataSource = blockedReports;

                //if (AppConfiguration.DataCached)
                //{
                //    foreach (DataColumn column in blockedReports.Columns)
                //    {
                //        DataGridViewColumn col = new DataGridViewColumn();
                //        col.Name = column.ColumnName;
                //        col.ReadOnly = true;
                //        col.ValueType = column.DataType;
                //        col.CellTemplate = new DataGridViewTextBoxCell();
                //        this.dgvBlockedReports.Columns.Add(col);
                //    }

                //    foreach (DataRow row in blockedReports.Rows)
                //    {
                //        int cellCount = row.ItemArray.Length;
                //        object[] objects = new object[cellCount];
                //        for (int i = 0; i < row.ItemArray.Length; i++) objects[i] = row.ItemArray[i];
                //        this.dgvBlockedReports.Rows.Add(objects);
                //    }
                //}
                //else this.dgvBlockedReports.DataSource = blockedReports;

                dgvBlockedReports.Columns[0].Visible = false;
                dgvBlockedReports.Columns[1].Visible = false;
                dgvBlockedReports.Columns[4].Visible = false;
                dgvBlockedReports.Columns[8].Visible = false;
                dgvBlockedReports.Columns[9].Visible = false;
                dgvBlockedReports.Columns[10].Visible = false;
                dgvBlockedReports.Columns[11].Visible = false;
                dgvBlockedReports.Columns[12].Visible = false;

                toolStripStatusLabel.Text = "Ready";

                cmdUnblock.Enabled = true;
                btnViewReportingHistory.Enabled = true;
                lblNoBlockedReport.Visible = false;

                blockedReportCount = dgvBlockedReports.Rows.Count;
                cmdUnblock.Enabled = (blockedReportCount > 0);
                lblBlockedCount.Text = String.Format("There are {0} blocked reporting", dgvBlockedReports.Rows.Count);
            }
            else
            {
                cmdUnblock.Enabled = false;
                btnViewReportingHistory.Enabled = false;
                lblNoBlockedReport.Visible = true;
                toolStripStatusLabel.Text = "Ready";
            }            
        }

        private void btnRefreshBlockedList_Click(object sender, EventArgs e)
        {
            try
            {
                txtSearchBlockedReports.Clear();
                Cursor.Current = Cursors.WaitCursor;
                btnRefreshBlockedList.Enabled = false;
                toolStripStatusLabel.Text = "Loading data, please wait...";
                Application.DoEvents();

                Utilities.ClearCache(DataCache.BLOCKED_REPORTS);
                tabPageBlockedReportsLoaded = false;
                tabPageBlockedReports_Enter(null, null);

                toolStripStatusLabel.Text = "Ready";
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
            finally
            {
                btnRefreshBlockedList.Enabled = true;
            }
        }

        private void txtSearchBlockedReports_TextChanged(object sender, EventArgs e)
        {
            string keyword = txtSearchBlockedReports.Text;
            DataTable dataSource = dgvBlockedReports.DataSource as DataTable;
            if (dataSource != null)
            {
                if (string.IsNullOrEmpty(keyword))
                {
                    // Reset everything back to the way it was.
                    dataSource.DefaultView.RowFilter = string.Empty;
                    lblBlockedCount.Text = string.Format("There are {0} blocked reporting", dataSource.DefaultView.Count);
                    lblBlockedCount.ForeColor = Color.Black;
                    cmdUnblock.Enabled = (dgvBlockedReports.Rows.Count > 0);
                    return;
                }

                string filterExpression = string.Format(
                    "Name LIKE '%{0}%' " +
                    "OR FacName LIKE '%{0}%' " +
                    "OR ReportName LIKE '%{0}%' " +
                    "OR SenderNum LIKE '%{0}%' " +
                    "OR FacCode LIKE '%{0}%' " +
                    "OR TxtDetails LIKE '%{0}%' " +
                    "OR ErrMsg LIKE '%{0}%'"
                    , keyword);

                dataSource.DefaultView.RowFilter = filterExpression;
                lblBlockedCount.Text = string.Format("Search Results: {0} blocked reporting", dataSource.DefaultView.Count);
                lblBlockedCount.ForeColor = Color.BlueViolet;
                cmdUnblock.Enabled = (dgvBlockedReports.Rows.Count > 0);
            }
        }
    }
}
